package com.demiroot.server;

import java.util.Stack;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class ServerConfigReader extends DefaultHandler {
	private Config config;
	private Stack<String> above = new Stack<String>();
	
	public ServerConfigReader(Config config) {
		this.config = config;
		above.push("START");
	}
	
	@Override
	public void characters(char[] ch, int start, int len) throws SAXException {
		 String text = new String( ch, start, len ); 
		 text = text.trim(); 
		 if( text.length() > 0 ) {
			 //do something with text
		 }
	}

	@Override
	public void endElement(String arg0, String arg1, String name)
			throws SAXException {
		above.pop();
	}

	@Override
	public void startElement(String arg0, String arg1, String name,	Attributes atrib) throws SAXException {
		if (above.peek().equals("server")) {
			if (name.equals("dnsupdate")) {
				String authToken = atrib.getValue("authToken");
				if (authToken == null) {
					throw new SAXException("Error in element dnsupdate, not attrubute \"authToken\" given.\n" +
							"AuthToken should be the base64 md5 hash of your zoneedit username : then password eg.\n" +
							"username:passwd");
				}
				config.setAuthToken(authToken);
			}
		} else if (above.peek().equals("dnsupdate")) {
			if (name.equals("site")) {
				String site = atrib.getValue("site");
				if (site != null) {
					config.addDNSSite(site);
				}
			}
		} else if (name.equals("location")) {
			String dir = atrib.getValue("dir");
			if (dir == null) {
				throw new SAXException("error: location tag needs a \"dir\" attribute");
			}
			String auth = atrib.getValue("auth");
			int authNum = -1;
			if (auth != null) {
				try {
					authNum = Integer.parseInt(auth);
				} catch (Exception e) {
					throw new SAXException("error: attribuate \"auth\" must be a number!,\n" +
							"could not convert " + auth + " to a number");
				}
			}
			if (above.peek().equals("htdocs")) {
				config.addHtdocsLoc(dir, authNum);
			} else if (above.peek().equals("java")) {
				config.addjdocsLoc(dir, authNum);
			} else if (above.peek().equals("templates")) {
				config.addTemplateLoc(dir, authNum);
			}
		} else if (above.peek().equals("java")) {
			if(name.equals("physical")) {
				config.setPhysicalPage(atrib.getValue("page"));
			} else if (name.equals("notFound")) {
				config.setNotFoundPage(atrib.getValue("page"));
			} else if (name.equals("proxyIntercept")) {
				config.setProxyIntercept(atrib.getValue("class"));
			}
		}
		above.push(name);
	}
}
